import {Component, HostListener, OnDestroy, OnInit} from "@angular/core";
import {CommService} from "../comm-service";
import {sjgzxinModuledatas} from "../pubcomponent/pageTitle.datas";
import {LocalStorageService} from "../local-storage-service";


declare var $: any;
declare var AMap: any;

@Component({
  template: `
  <div class="all_bg paddingTop">
    <div class="">
      <div class="portlet-body">
        <div class="tabbable-custom nav-justified">
          <ul class="nav nav-tabs nav-justified">
            <!--<li class="active"><a href="#yycl" data-toggle="tab" (click)="tab('yycl')">押运车辆</a>-->
            <!--&lt;!&ndash; <div class="arrdowm"></div> &ndash;&gt;-->
            <!--</li>-->
            <li class="active"><a href="#sczd" data-toggle="tab" (click)="tab('sczd')">手持终端</a>
              <!-- <div class="arrdowm"></div> -->
            </li>
            <li><a href="#dzbq" data-toggle="tab" (click)="tab('dzbq')">电子标签</a>
              <!-- <div class="arrdowm"></div> -->
            </li>
          </ul>
          <div class="tab-content">
            <!--押运车辆-->
            <!--<div class="tab-pane active" id="yycl">-->
            <!--<div class="row">-->
            <!--<form class="form-horizontal" role="form">-->
            <!--<div class="col-lg-4">-->
            <!--<div class="form-group">-->
            <!--<label class="col-lg-3 control-label">车辆状态：</label>-->
            <!--<div class="col-lg-8">-->
            <!--<select class="form-control" id="clztSelect" name="clzt" [(ngModel)]="s_obj_yycl.zt">-->
            <!--<option value="">全部</option>-->
            <!--<option value="">离线</option>-->
            <!--<option value="">静止</option>-->
            <!--<option value="">运动</option>-->
            <!--</select>-->
            <!--</div>-->
            <!--</div>-->
            <!--</div>-->
            <!--<div class="col-lg-4">-->
            <!--<div class="form-group">-->
            <!--<label class="control-label col-lg-3">车辆名称：</label>-->
            <!--<div class="col-lg-8">-->
            <!--<input type="text" class="form-control" placeholder="请输入车辆名称"/>-->
            <!--</div>-->
            <!--</div>-->
            <!--</div>-->
            <!--<div class="col-lg-2">-->
            <!--<button type="button" class="btn blue" (click)="inittable_yycl()">-->
            <!--<i class="fa fa-search"></i> 搜索-->
            <!--</button>&nbsp;&nbsp;&nbsp;&nbsp;-->
            <!--</div>-->
            <!--</form>-->
            <!--</div>-->
            <!--<div class="row">-->
            <!--<div class="col-lg-12" *ngIf="table_yycl">-->
            <!--<my-table [o]="table_yycl"></my-table>-->
            <!--</div>-->
            <!--</div>-->
            <!--</div>-->
            <!--手持终端-->
            <div class="tab-pane active" id="sczd">
              <div class="row">
                <form class="form-horizontal" role="form">
                  <div class="col-lg-4 col-lg-offset-6">
                    <div class="form-group">
                      <label class="control-label col-lg-3" for="cxtj_zd">查询条件：</label>
                      <div class="col-lg-9">
                        <input type="text" id="cxtj_zd" name="cxtj" class="form-control"
                               placeholder="市区名称/考区名称/保密室名称/终端名称/终端ID" [(ngModel)]="s_obj_sczd.cxtj"/>
                      </div>
                    </div>
                  </div>
                  <div class="col-lg-2">
                    <button type="button" class="btn blue" (click)="inittable_sczd()">
                      <i class="fa fa-search"></i> 搜索
                    </button>&nbsp;&nbsp;&nbsp;&nbsp;
                  </div>
                </form>
              </div>
              <div class="row">
                <div class="col-lg-12" *ngIf="table_sczd">
                  <my-table [o]="table_sczd"></my-table>
                </div>
              </div>
            </div>
            <!--电子标签-->
            <div class="tab-pane" id="dzbq">
              <div class="row">
                <form class="form-horizontal" role="form">
                  <div class="col-lg-4">
                    <div class="form-group">
                      <label class="col-lg-3 control-label">设备状态：</label>
                      <div class="col-lg-8">
                        <select class="form-control" id="dzbqSelect" name="sbzt" [(ngModel)]="s_obj_dzbq.zt">
                          <option value="">全部</option>
                          <option value="">离线</option>
                          <option value="">静止</option>
                          <option value="">运动</option>
                        </select>
                      </div>
                    </div>
                  </div>
                  <div class="col-lg-4">
                    <div class="form-group">
                      <label class="control-label col-lg-3">标签名称：</label>
                      <div class="col-lg-8">
                        <input type="text" class="form-control"/>
                      </div>
                    </div>
                  </div>
                  <div class="col-lg-2">
                    <button type="button" class="btn blue" (click)="inittable_dzbq()">
                      <i class="fa fa-search"></i> 搜索
                    </button>&nbsp;&nbsp;&nbsp;&nbsp;
                  </div>
                </form>
              </div>
              <div class="row">
                <div class="col-lg-12" *ngIf="table_dzbq">
                  <my-table [o]="table_dzbq"></my-table>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="modal fad" id="addressModal" tabindex="-1" role="dialog"
         aria-labelledby="myModalLabel">
      <div class="modal-dialog bigmodalwidth" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
              aria-hidden="true">&times;</span></button>
            <h4 class="modal-title" id="myModalLabel">地址</h4>
          </div>
          <div class="modal-body">
            <div id="mapdiv" class="mapdiv"></div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">关 闭</button>
          </div>
        </div>
      </div>
    </div>
    </div>
  `,
  styles: [
    ".mapdiv{width: 100%;height:600px;}",
  ]
})
export class TjbbSbxqComponent implements OnInit, OnDestroy {
  activetab: string = "sczd";
  // s_obj_yycl: any = {
  //   zt: "",
  //   kslx: ''
  // }
  // table_yycl: any;
  s_obj_sczd: any = {
    ksgljgid: "",  //b
    cxtj: ''   // 市区名称/考区名称/保密室名称/终端名称/终端ID
  }
  table_sczd: any;
  s_obj_dzbq: any = {
    ksgljgid: "",  //b
    ksjhbh: '',   //b
    cxtj: "",   // 市区名称/考区名称/保密室名称/标签ID
  }
  table_dzbq: any;

  nowaddressMarker: any;
  map: any;
  geocoder: any;

  tab(activetab: string): void {
    this.activetab = activetab;
    this.search_n();
  }

  search_n(): void {
    // if (this.activetab == "yycl") {
    //   this.inittable_yycl();
    // } else
    //
    if (this.activetab == "sczd") {
      this.inittable_sczd();
    } else if (this.activetab == "dzbq") {
      this.inittable_dzbq();
    }
  }

  // inittable_yycl(): void {
  //   const that = this;
  //   this.table_yycl = {
  //     tableid: "table_yycl",
  //     url: "sjgz/rwjh/cxsjcrklb",
  //     reqobj: "",
  //     sidePagination: "server",
  //     pageSize: 10,
  //     pageList: [10, 20, 30],
  //     total: "totalRows",
  //     rows: "",
  //     columns: [{
  //       title: "序号",
  //       field: "zbmc",
  //     }, {
  //       title: "车辆名称",
  //       field: "kdmc",
  //     }, {
  //       title: "车辆类型",
  //       field: "sjbmc",
  //     }, {
  //       title: "车辆品牌",
  //       field: "sjbzt",
  //     }, {
  //       title: "车辆来源",
  //       field: "dqdz",
  //     }, {
  //       title: "车牌号",
  //       field: "jwd",
  //     }, {
  //       title: "车辆状态(静止,离线,运动)",
  //       field: "bh",
  //       //events: this.myevents,
  //       formatter: function (v) {
  //         let str: string = "";
  //         str += "<button type='button' class='btn btn-xs btn-info xq_yjjy'><i class='fa fa-search'></i> 详情</button>";
  //         return str;
  //       }
  //     }, {
  //       title: "最近一次通信时间",
  //       field: "jwd",
  //     }, {
  //       title: "最后一次位置",
  //       field: "jwd",
  //     }, {
  //       title: "经纬度",
  //       field: "jwd",
  //     }, {
  //       title: "车辆所属单位",
  //       field: "jwd",
  //     }]
  //   };
  //   this.table_yycl.height = this.commservice.getViewPort().height - this.commservice.topH - this.commservice.topmenuH - 240 - 50;
  // }

  inittable_sczd(): void {
    const that = this;
    this.table_sczd = {
      tableid: "table_sczd",
      url: "sjgz/zsymtjbb/sczdsbxq",
      reqobj: this.s_obj_sczd,
      sidePagination: "server",
      pageSize: 10,
      pageList: [10, 20, 30],
      total: "totalRows",
      rows: "sczdsbList",
      columns: [{
        title: "序号",
        field: "ordernum",
      }, {
        title: "设备名称",
        field: "sczdmc",
      }, {
        title: "ID",
        field: "id",
      }, {
        title: "设备SIM卡号",
        field: "sjhm",
      }, {
        title: "设备型号",
        field: "xh",
      }, {
        title: "设备状态",
        field: "zxzt",
        formatter: function (v, row) {
          let str: string = "";
          const sdv = row.sd ? row.sd : "";
          if (v == "1") {
            str = "离线";
          } else {
            if (Number(sdv) > 0) {
              str = "运动";
            } else {
              str = "静止";
            }
          }
          return str;
        }
      }, {
        title: "最后一次通信时间",
        field: "zjxtsj",
      }, {
        title: "经纬度",
        field: "jwd",
        events: this.myevents,
        formatter: function (v, row) {
          const jdv = row.jd;
          const wdv = row.wd;
          let str: string = "";
          if (jdv && wdv) {
            str += "<span class='showAddress' style='cursor: pointer;text-decoration-line: underline;color: blue'>" + [jdv, wdv].join("/") + "</span>";
          }
          return str;
        }
      }, {
        title: "最后一次位置",
        field: "sczdbh",
        events: this.myevents,
        formatter: function (v, row) {
          const jdv = row.jd;
          const wdv = row.wd;
          let str: string = "";
          if (jdv && wdv) {
            if (v.indexOf("|") == -1) {
              str += "<span class='getAddress' style='cursor: pointer;text-decoration-line: underline;color: blue'>查看地址</span>";
            } else {
              str += v.substring(1);
            }
          }
          return str;
        }
      }, {
        title: "电量",
        field: "dl",
        formatter: function (v) {
          let str: string = "";
          if (v) {
            str += `${v}%`;
          }
          return str;
        }
      }]
    };
    this.table_sczd.height = this.commservice.getViewPort().height - this.commservice.topH - this.commservice.topmenuH - 240 - 100;
  }

  inittable_dzbq(): void {
    const that = this;
    this.table_dzbq = {
      tableid: "table_dzbq",
      url: "sjgz/zsymtjbb/dzbqsbxq",
      reqobj: this.s_obj_dzbq,
      sidePagination: "server",
      pageSize: 10,
      pageList: [10, 20, 30],
      total: "totalRows",
      rows: "dzbqsbList",
      columns: [{
        title: "序号",
        field: "ordernum",
      }, {
        title: "试卷包名称",
        field: "bdsjbmc",
      }, {
        title: "设备ID",
        field: "id",
      }, {
        title: "设备状态（静止,离线,运动）",
        field: "zxzt",
        formatter: function (v, row) {
          const sdv = row.sd ? row.sd : "";
          let str: string = "";
          if (v == "1") {
            str = "离线";
          } else {
            if (Number(sdv) > 0) {
              str = "运动";
            } else {
              str = "静止";
            }
          }
          return str;
        }
      }, {
        title: "最近一次通信时间",
        field: "zjxtsj",
      }, {
        title: "最后一次位置",
        field: "dzbqbh",
        events: this.myevents,
        formatter: function (v, row) {
          const jdv = row.jd;
          const wdv = row.wd;
          let str: string = "";
          if (jdv && wdv) {
            if (v.indexOf("|") == -1) {
              str += "<span class='getAddress_bq' style='cursor: pointer;text-decoration-line: underline;color: blue'>查看地址</span>";
            } else {
              str += v.substring(1);
            }
          }
          return str;
        }
      }, {
        title: "经纬度",
        field: "jwd",
        events: this.myevents,
        formatter: function (v, row) {
          const jdv = row.jd;
          const wdv = row.wd;
          let str: string = "";
          if (jdv && wdv) {
            str += "<span class='showAddress' style='cursor: pointer;text-decoration-line: underline;color: blue'>" + [jdv, wdv].join("/") + "</span>";
          }
          return str;
        }
      }, {
        title: "ESIM串号",
        field: 'iccid'
      }, {
        title: "GNSS状态",
        field: "cat1mkzt",
      }, {
        title: "GNSS电量",
        field: "gnssdl",
        formatter: function (v) {
          let str: string = "";
          if (v) {
            str = `${v}%`;
          }
          return str;
        }
      }]
    };
    this.table_dzbq.height = this.commservice.getViewPort().height - this.commservice.topH - this.commservice.topmenuH - 240 - 100;
  }


  @HostListener("window:myevents", ["$event"])
  myevents = {
    "click .getAddress": function (e, value, row, index) {
      const jdv = row.jd;
      const wdv = row.wd;
      if (jdv && wdv) {
        this.getAddresss([jdv, wdv], (resp) => {
          const dzmc = resp.regeocode.formattedAddress;
          const Flagbit = "|";
          $("#table_sczd").bootstrapTable("updateCell", {index: index, field: "sczdbh", value: Flagbit + dzmc});
        });
      }
    }.bind(this),
    "click .showAddress": function (e, value, row, index) {
      const jdv = row.jd;
      const wdv = row.wd;
      if (jdv && wdv) {
        this.nowaddressMarker.setPosition([jdv, wdv]);
        this.getAddresss([jdv, wdv], (resp) => {
          const dzmc = resp.regeocode.formattedAddress;
          this.nowaddressMarker.setLabel({
            offset: new AMap.Pixel(10, 0),  //设置文本标注偏移量
            content: dzmc,
            direction: 'bottom' //设置文本标注方位
          })
        });
        this.map.setZoomAndCenter(10, [jdv, wdv]);
        $("#addressModal").modal({
          keyboard: true,
          backdrop: "static"
        });
      }
    }.bind(this),
    "click .getAddress_bq": function (e, value, row, index) {
      const jdv = row.jd;
      const wdv = row.wd;
      if (jdv && wdv) {
        this.getAddresss([jdv, wdv], (resp) => {
          const dzmc = resp.regeocode.formattedAddress;
          const Flagbit = "|";
          $("#table_dzbq").bootstrapTable("updateCell", {index: index, field: "dzbqbh", value: Flagbit + dzmc});
        });
      }
    }.bind(this),
  }

  getAddresss(lnglatXY: any, callback: Function): void {
    this.geocoder.getAddress(lnglatXY, function (status, result) {
      if (status === 'complete' && result.info === 'OK') {
        callback(result);
      }
    });
  }

  initMap(): void {
    const that = this;
    this.map = new AMap.Map("mapdiv", {
      resizeEnable: true, //是否监控地图容器尺寸变化，默认值为false
      zoom: 11, //地图显示的缩放级别，若center与level未赋值，地图初始化默认显示用户所在城市范围，没有center（中心点）和level ，所以这个暂时无效
    });
    this.nowaddressMarker = new AMap.Marker({
      map: that.map,
      //position: markobj.position,
      offset: new AMap.Pixel(-17, -14),
      //angle: Number(markobj.fxj) + 90 + 180,
      zIndex: 100,  //默认值是100
    });

    AMap.plugin(['AMap.Geocoder'],
      function () {
        that.geocoder = new AMap.Geocoder({
          radius: 1000,
          extensions: "all"
        });
      });
  }

  /**
   * 获取用户信息
   */
  getuserinfo(): void {
    this.commservice.getUserinfo((info) => {
      this.s_obj_sczd.ksgljgid = info.csid;
      this.s_obj_dzbq.ksgljgid = info.csid;
      this.inittable_sczd();
    });
  }

  constructor(private commservice: CommService,
              private localStorageService: LocalStorageService) {

  }

  ngOnInit() {
    this.s_obj_dzbq.ksjhbh = this.localStorageService.get("hksjh");
    this.initMap();
    this.getuserinfo();

  }

  ngOnDestroy() {

  }

}
